package com.kugua.zfms.rank.impl;

import com.kugua.zfms.rank.Rank;
import com.kugua.zfms.rank.pojo.RankObject;
import com.kugua.zfms.rank.pojo.RankScore;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.stereotype.Component;

import java.util.LinkedHashSet;
import java.util.Set;

/**
 * <p>TODO</p>
 * <p>
 * <PRE>
 * <BR>    修改记录
 * <BR>-----------------------------------------------
 * <BR>    修改日期         修改人          修改内容
 * </PRE>
 *
 * @author cuiyh9
 * @version 1.0
 * @Date Created in 2019年01月07日 15:54
 * @since 1.0
 */
@Component
public class RedisRank implements Rank {

    private static final String RANK_KEY_DEMO = "rankKeyDemo1";

    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public int size() {
        long size = redisTemplate.opsForZSet().size(RANK_KEY_DEMO);
        return (int)size;
    }

    @Override
    public Set<Long> page(int page, int size) {
        int start =(page -1) * size;
        if (start < 0) {
            start = 0;
        }
        int end = page * size;
        Set<Long> rankScoresSet = redisTemplate.opsForZSet().reverseRangeWithScores(RANK_KEY_DEMO, start, end);
        return rankScoresSet;
    }

    @Override
    public Set<Long> list() {
        int size = size();
        Set<ZSetOperations.TypedTuple<Integer>> typedTuple = redisTemplate.opsForZSet().reverseRangeWithScores(RANK_KEY_DEMO, 0, size);
        Set<Long> set = new LinkedHashSet<>();
        for (ZSetOperations.TypedTuple<Integer> rankScoreTypedTuple : typedTuple) {
            set.add(Long.valueOf(rankScoreTypedTuple.getValue()));
        }
        return set;
    }

    @Override
    public void add(RankObject rankObject) {
        long score = RankScore.calculateScore(rankObject);
        boolean flag = redisTemplate.opsForZSet().add(RANK_KEY_DEMO, rankObject.getId(), Double.valueOf(score));
    }

    @Override
    public int getRank(long id) {
        long index = redisTemplate.opsForZSet().rank(RANK_KEY_DEMO, id);
        return (int)index;
    }
}
